package com.zbkj.crmeb.handler.orderproduct;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.exception.CrmebException;
import com.factory.PushWarehouseFactory;
import com.utils.PriceUtil;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.impl.CategoryMatchServiceImpl;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.BusinessTypeEnums;
import com.zbkj.crmeb.enums.plat.PlatPushStatusEnums;
import com.zbkj.crmeb.merchant.api.service.MerProductService;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.plat.by.dto.PoizonPushInfo;
import com.zbkj.crmeb.plat.by.dto.Result;
import com.zbkj.crmeb.plat.by.dto.attributes.SaleAttribute;
import com.zbkj.crmeb.plat.enums.MerPlatEnums;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.task.plat.poizon.PoizonApi;
import com.zbkj.crmeb.task.plat.poizon.dto.PoizonPushStockUpdateDto;
import com.zbkj.crmeb.task.plat.poizon.dto.PoizonPushStockUpdateDto.Spu;
import com.zbkj.crmeb.task.plat.poizon.dto.PoizonResponseBodyDto;
import com.zbkj.crmeb.tools.model.MoneyExchange;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: wsl
 * @date: 2024/2/22 0022 22:28
 * @ClassName: ByOrderConfirmHandler
 */
@Component("poizonOrderProductHandler")
public class PoizonOrderProductHandler extends AbstractOrderProductHandler {
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private MerProductService productService;
    @Autowired
    private MoneyExchangeService moneyExchangeService;
    @Autowired
    private StoreProductLogService storeProductLogService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private StoreBrandService storeBrandService;
    @Autowired
    private PushWarehouseFactory pushWarehouseFactory;
    @Autowired
    private RelationService relationService;
    @Autowired
    private PoizonApi poizonApi;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private CategoryService categoryService;

    private static final Logger logger = LoggerFactory.getLogger(PoizonOrderProductHandler.class);

    @Override
    public boolean doPreCheck(OrderProductContext context) {
        return true;
    }

    @Override
    public Result doHandler(OrderProductContext context) {
        Result result = new Result();
        String productId = context.getProductId();
        // 查询商品信息
        StoreProduct storeProduct = context.getStoreProduct();
        if (null == storeProduct) {
            storeProduct = storeProductService.getById(productId);
            context.setStoreProduct(storeProduct);
        }
        // 查询sku信息
        List<StoreProductAttrValue> storeProductAttrValues = context.getStoreProductAttrValues();
        if (CollectionUtils.isEmpty(storeProductAttrValues)) {
            storeProductAttrValues = storeProductAttrValueService.getListByProductId(Integer.valueOf(productId));
            context.setStoreProductAttrValues(storeProductAttrValues);
        }
        List<String> validateList = new ArrayList<>();
        // 组装得物商品参数
        PoizonPushStockUpdateDto dto = assembledProduct(context, storeProduct, storeProductAttrValues, validateList);
        context.setValidateList(validateList);
        if (null == dto || CollectionUtils.isNotEmpty(validateList)) {
            result.setData(validateList);
            result.setSuccess(false);
            return result;
        }
        // 推送得物平台
        PoizonResponseBodyDto<PoizonResponseBodyDto.PushStockUpdateDataDTO> responseBodyDto = poizonApi.pushIncrement(dto);
        String response = JSON.toJSONString(responseBodyDto);
        //        DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"推送商品记录："+response);
        logger.error("推送商品记录:{}", response);
        // 失败
        if (!responseBodyDto.getData().getPushResult()) {
            PoizonResponseBodyDto.PushStockUpdateDataDTO data = responseBodyDto.getData();
            String errorMessage = String.join(",", data.getFailEntry().getMessage());
            validateList.add(errorMessage);
            result.setData(validateList);
            result.setMessage(errorMessage);
            result.setSuccess(false);
            context.setValidateList(validateList);
            return result;
        }
        // 解析返回数据
        if (CollectionUtils.isNotEmpty(validateList)) {
            result.setData(validateList);
        }
        context.setPoizonApiProduct(dto);
        result.setSuccess(true);
        context.setValidateList(validateList);
        return result;
    }

    private void matchCategoryAndBrand(OrderProductContext context, StoreProduct storeProduct) {
        Integer cateId = storeProduct.getCateId();
        Integer brandId = storeProduct.getBrandId();
        if (null == cateId || null == brandId) {
            throw new CrmebException("商品分类或者品牌缺失");
        }
        CategoryMatch categoryMatch = categoryMatchService.getById(cateId);
        if (null != categoryMatch) {
            context.setCategoryId(categoryMatch.getByCategoryId());
            context.setCategoryName(categoryMatch.getCategoryName());
        }
        StoreBrand storeBrand = storeBrandService.getById(brandId);
        if (null != storeBrand) {
            context.setBrandId(storeBrand.getByBrandId());
            context.setBrandName(storeBrand.getEnName());
        }

    }

    @Override
    public void doAfter(OrderProductContext context, Result result) {
        PoizonPushStockUpdateDto poizonApiProduct = context.getPoizonApiProduct();
        // 处理商品数据
        handleProductAfter(poizonApiProduct, context, result);
        // 处理SKU数据
        handleSkuAfter(poizonApiProduct, context, result);
    }

    private void handleProductAfter(PoizonPushStockUpdateDto poizonApiProduct, OrderProductContext context, Result result) {
        StoreProduct storeProduct = context.getStoreProduct();
        // 更新推送标记
        String pushPlat = result.isSuccess() ? PlatPushStatusEnums.DW_UP.getCode() : PlatPushStatusEnums.DW_DOWN.getCode();
        Relation productRelation = relationService.getOne(Wrappers.<Relation>lambdaQuery().eq(Relation::getBusinessCode, storeProduct.getId()).eq(Relation::getBusinessType, BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_DW.getCode()));
        if (null == productRelation) {
            productRelation = Relation.buildRelation(String.valueOf(storeProduct.getId()), BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_DW, pushPlat);
        }
        productRelation.setSubCode(pushPlat);
        String msg = result.isSuccess() ? "商品推送得物平台成功" : "推送失败:" + result.getMessage();
        if (null != poizonApiProduct) {
            productRelation.addFeature(ByCommonConstant.PLAT_PRODUCT_ID, poizonApiProduct.getSpu().getSpuId());
            productRelation.addFeature(ByCommonConstant.MERCHANT_PRODUCT_ID, poizonApiProduct.getSpu().getSpuId());
        }
        if (null == productRelation.getId()) {
            relationService.save(productRelation);
        } else {
            relationService.updateById(productRelation);
        }
        List<String> validateList = context.getValidateList();
        // 保存日志
        List<StoreProductLog> storeProductLogs = new ArrayList<>();
        storeProductLogs.add(StoreProductLog.assembledLog(String.valueOf(storeProduct.getId()), msg));
        validateList.forEach(item -> storeProductLogs.add(StoreProductLog.assembledLog(String.valueOf(storeProduct.getId()), ByCommonConstant.POIZON_PLAT_PUSH_LOG, item)));
        storeProductLogService.saveOrUpdateBatch(storeProductLogs);
    }

    private void handleSkuAfter(PoizonPushStockUpdateDto poizonApiProduct, OrderProductContext context, Result result) {
        if (null == poizonApiProduct) {
            return;
        }
        List<StoreProductAttrValue> storeProductAttrValues = context.getStoreProductAttrValues();
        if (CollectionUtils.isEmpty(storeProductAttrValues)) {
            return;
        }
        Map<Integer, StoreProductAttrValue> map = new HashMap<>();
        List<String> attrValueIds = new ArrayList<>();
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            map.put(storeProductAttrValue.getId(), storeProductAttrValue);
            attrValueIds.add(String.valueOf(storeProductAttrValue.getId()));
        }
        List<Relation> relations = relationService.list(Wrappers.<Relation>lambdaQuery().in(Relation::getBusinessCode, attrValueIds).eq(Relation::getBusinessType, BusinessTypeEnums.PUSH_SKU_PLAT_OF_DW.getCode()));
        Map<String, Relation> relationMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(relations)) {
            relationMap = relations.stream().collect(Collectors.toMap(Relation::getBusinessCode, v -> v));
        }
        List<Relation> updateRelations = new ArrayList<>();
        List<Relation> insertRelations = new ArrayList<>();
        for (PoizonPushStockUpdateDto.Sku skus : poizonApiProduct.getSpu().getSkus()) {
            String[] split = skus.getSkuId().split("SUYUN");
            StoreProductAttrValue storeProductAttrValue = map.get(Integer.valueOf(split[1]));
            Relation skuRelation = relationMap.get(skus.getSkuId());
            if (null == skuRelation) {
                skuRelation = Relation.buildRelation(split[1], BusinessTypeEnums.PUSH_SKU_PLAT_OF_DW, PlatPushStatusEnums.DW_UP.getCode());
                insertRelations.add(skuRelation);
            } else {
                updateRelations.add(skuRelation);
            }
            skuRelation.addFeature(ByCommonConstant.PUSH_PLAT, "Y");
            skuRelation.addFeature(ByCommonConstant.ORIGIN_STOCK, String.valueOf(storeProductAttrValue.getStock()));
            skuRelation.addFeature(ByCommonConstant.PUSH_PRICE, String.valueOf(storeProductAttrValue.getPrice()));
            skuRelation.addFeature(ByCommonConstant.PLAT_SKU_ID, poizonApiProduct.getSpu().getSkus().get(0).getSkuId());
            skuRelation.addFeature(ByCommonConstant.MERCHANT_SKU_ID, poizonApiProduct.getSpu().getSkus().get(0).getSkuId());

            if (null != skus.getRetailPrice()) {
                skuRelation.addFeature(ByCommonConstant.PLAT_SALE_PRICE, skus.getRetailPrice());
            }
            if (null != skus.getPurchasePrice()) {
                skuRelation.addFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE, skus.getPurchasePrice());
            }
        }
        if (CollectionUtils.isNotEmpty(updateRelations)) {
            for (Relation updateRelation : updateRelations) {
                relationService.updateById(updateRelation);
            }
        }
        if (CollectionUtils.isNotEmpty(insertRelations)) {
            relationService.saveBatch(insertRelations);
        }
    }

    private PoizonPushStockUpdateDto assembledProduct(OrderProductContext context, StoreProduct storeProduct, List<StoreProductAttrValue> storeProductAttrValues, List<String> validateList) {
        PoizonPushInfo poizonPushInfo = context.getPoizonPushInfo();
        priceUtil.calcProductValuePrice(storeProductAttrValues, context.getMerId(), storeProduct, AreaTypeEnum.ABROAD.getType(), null, false, null, true, null);
        PoizonPushStockUpdateDto poizonPushStockUpdateDto = new PoizonPushStockUpdateDto();
        Spu spu = new Spu();
        spu.setSpuId("lavita_" + context.getMerId() + "_" + storeProduct.getKeyword());
        spu.setSpuName(storeProduct.getStoreName() + " " + storeProduct.getKeyword());
        spu.setBrandName(poizonPushInfo.getBrandData().getCheckItem());
        spu.setDesignerId(storeProduct.getKeyword());
        spu.setCategoryL1(poizonPushInfo.getCategoryData().getCheckItem());
        spu.setGender(poizonPushInfo.getGanderData().getCheckItem());
        String season = storeProduct.getSeasonCode();
        if (StringUtils.isBlank(season)) {
            season = "CarryOver";
        }
        spu.setSeason(season);
        String productErrorKey = String.format("商品名:%s--->商品id:%s--->异常信息: ", storeProduct.getStoreName(), storeProduct.getId());
        StoreProductDescription storeProductDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery().eq(StoreProductDescription::getProductId, storeProduct.getId()));
        if (StringUtils.isBlank(storeProductDescription.getSliderImage())) {
            validateList.add(productErrorKey + "商品缺失主图或轮播图");
            return null;
        }
        // 获取商品属性信息
        List<StoreProductAttr> storeProductAttrs = storeProductAttrService.getByProductId(storeProduct.getId());
        if (CollectionUtils.isEmpty(storeProductAttrs)) {
            validateList.add(productErrorKey + "商品缺失属性规格");
            return null;
        }
        Map<String, StoreProductAttr> attrMap = storeProductAttrs.stream().collect(Collectors.toMap(StoreProductAttr::getAttrName, Function.identity(), (s1, s2) -> s1));

        String sliderImage = storeProductDescription.getSliderImage();
        List<String> split = JSON.parseArray(sliderImage, String.class);
        spu.setImages(split);
        spu.setDesc(storeProductDescription.getDescription());
        poizonPushStockUpdateDto.setSpu(spu);


        // 计算金额
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("merId", MerPlatEnums.POIZON_142.getMerId());
        THREAD_LOCAL.set(jsonObject);
        MoneyExchange moneyExchange = moneyExchangeService.getById(11);
        BigDecimal baseExchange = new BigDecimal("7.2");
        if (null != moneyExchange && StringUtils.isNotBlank(moneyExchange.getBankConversionPri())) {
            baseExchange = new BigDecimal(moneyExchange.getBankConversionPri());
        }
        // sku数据
        List<PoizonPushStockUpdateDto.Sku> skus = new ArrayList<>();
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            String skuErrorKey = String.format("商品名:%s--->sku信息:%s--->异常信息: ", storeProduct.getStoreName(), storeProductAttrValue.getSuk());
            // sku
            PoizonPushStockUpdateDto.Sku sku = new PoizonPushStockUpdateDto.Sku();
            sku.setSkuId("SUYUN" + storeProductAttrValue.getId());
//            sku.setBarcode(Long.valueOf(storeProductAttrValue.getId()));
            if (StringUtils.isBlank(storeProductAttrValue.getAttrValue()) && MapUtils.isEmpty(attrMap)) {
                validateList.add(skuErrorKey + "sku缺少产品属性");
                continue;
            }

            JSONObject skuAttribute = JSON.parseObject(StringUtils.defaultString(storeProductAttrValue.getAttrValue(), "{}"));
            String size = (String) skuAttribute.get("尺寸");
            if (StringUtils.isBlank(size)) {
                size = (String) skuAttribute.get("尺码");
            }
            if (StringUtils.isBlank(size)) {
                validateList.add(skuErrorKey + "sku缺少尺寸");
                continue;
            }
            sku.setSize(size);
            sku.setSizeType(poizonPushInfo.getSizeTypeData().getCheckItem());
            // 免税采购价，指的是POIZON从商⼾采购
            BigDecimal purchasePrice = storeProductAttrValue.getPrice()
                    .divide(baseExchange, 2, RoundingMode.DOWN).setScale(2, RoundingMode.DOWN);
            sku.setPurchasePrice(purchasePrice.toString());
            // 含税零售市场价(使用price重新算税)
            ChannelMerchant mockChannelMerchant = new ChannelMerchant();
            BigDecimal taxPriceNew = priceUtil.getTaxPriceNew(storeProduct, AreaTypeEnum.ABROAD.getType(),
                    purchasePrice, mockChannelMerchant, purchasePrice, false, false, false);
            BigDecimal taxPrice = storeProductAttrValue.getTaxPrice().compareTo(taxPriceNew) >= 0 ? storeProductAttrValue.getTaxPrice() : taxPriceNew;
            sku.setRetailPrice(purchasePrice.add(taxPrice).setScale(2, RoundingMode.DOWN).toString());
            sku.setStock(storeProductAttrValue.getStock());
            skus.add(sku);
        }
        if (CollectionUtils.isEmpty(skus)) {
            validateList.add(productErrorKey + "当前商品没有满足上架条件SKU");
            return null;
        }
        spu.setSkus(skus);
        return poizonPushStockUpdateDto;

    }

}
